package com.autumn.scheduler.queue;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.DisposableBean;

import com.autumn.mq.FastJsonMessageConverter;
import com.autumn.mq.IAutumnQueue;
import com.autumn.mq.rabbit.RabbitDirectQueueDeclareFactory;
import com.autumn.mq.rabbit.annotation.AutumnRabbitConnection;
import com.autumn.scheduler.api.QueueJobEventData;
import com.autumn.spring.boot.context.AutumnApplicationContext;
import com.autumn.spring.boot.properties.PropertiesConstant;

/**
 * 队列上下文
 * 
 * @author 老码农
 *
 *         2018-03-19 16:18:42
 */
public class QueueContext implements DisposableBean {

	private final static Map<String, IAutumnQueue> Job_queue = new ConcurrentHashMap<>();

	/**
	 * 队列Bean前缀
	 */
	public final static String QUEUE_BEAN_PREFIX = PropertiesConstant.AUTUMN_MESSAGE_BENA_PREFIX;

	/**
	 * 获取或创建队列
	 * 
	 * @param queueName
	 *            队列名称
	 * @return
	 *
	 */
	public static IAutumnQueue getOrCreateAutumnQueue(String queueName) {
		String fullQueueName = QueueJobEventData.JOB_QUEUE_PREFIX + queueName;
		return Job_queue.computeIfAbsent(fullQueueName, key -> createAutumnQueue(key));
	}

	/**
	 * 连接工厂 Bean 名称
	 */
	public static final String connectFactoryBeanName = QUEUE_BEAN_PREFIX
			+ AutumnRabbitConnection.CONNECTION_FACTORY_BEAN_SUFFIX;

	/**
	 * 创建队列
	 * 
	 * @param fullQueueName
	 *            完成的队列名称
	 * @return
	 *
	 */
	private static IAutumnQueue createAutumnQueue(String fullQueueName) {
		CachingConnectionFactory connectFactory = AutumnApplicationContext.getContext().getBean(connectFactoryBeanName,
				CachingConnectionFactory.class);
		RabbitTemplate rabbitTemplate = new RabbitTemplate(connectFactory);
		rabbitTemplate.setMessageConverter(new FastJsonMessageConverter());
		RabbitDirectQueueDeclareFactory queryFactory = new RabbitDirectQueueDeclareFactory(fullQueueName);
		RabbitDirectQueueDeclareFactory.RabbitAutumnQueue queue = new RabbitDirectQueueDeclareFactory.RabbitAutumnQueue(
				queryFactory);
		queue.setRabbitTemplate(rabbitTemplate);
		queue.initialize();
		return queue;
	}

	@Override
	public void destroy() throws Exception {
		Job_queue.clear();
	}
}
